package org.ba.ovk.parser;

import java.io.IOException;

import lombok.AllArgsConstructor;
import lombok.val;

import org.apache.poi.hpsf.PropertySet;
import org.apache.poi.hpsf.SummaryInformation;
import org.apache.poi.poifs.filesystem.DocumentEntry;
import org.apache.poi.poifs.filesystem.DocumentInputStream;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.ba.ovk.msg.ParseProgramMsg;

import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;

@AllArgsConstructor
public class ParseProgramHandler {
	public EventBus bus;

	@Subscribe
	public void handleSendEmailCommand(final ParseProgramMsg command) {
		String out = command.ovkId + "," + command.candidateName + "," + command.partyName + "," + command.docUrl + ",";

		try (val is = command.docUrl.openStream()) {
			try {
				val pfis = new POIFSFileSystem(is);
				val dir = pfis.getRoot();
				val siEntry = (DocumentEntry) dir.getEntry(SummaryInformation.DEFAULT_STREAM_NAME);
				val dis = new DocumentInputStream(siEntry);
				val ps = new PropertySet(dis);
				val si = new SummaryInformation(ps);
				out =
						out + si.getAuthor() + "," + si.getLastAuthor() + "," + si.getCreateDateTime() + ", " + si.getLastSaveDateTime() + ","
								+ si.getTemplate() + "," + si.getOSVersion() + ", word(<2007)";
			}
			catch (IOException ioe) {
				val doc = new XWPFDocument(is);
				out =
						out + doc.getProperties().getCoreProperties().getCreator() + ",--,"
								+ doc.getProperties().getCoreProperties().getCreated() + ",--,--,word(>2007)";
			}

		}
		catch (Exception e) {
			out = out + "--" + "," + "--" + "," + "--" + "," + "--" + "," + "--" + "," + e.getLocalizedMessage();

		}

		System.out.println(out);
	}
}
